from flask import Flask,jsonify,render_template,request,escape
from gaode import geocode,around
from panduan import panduan_login
from weatherapi import weather
from pymysql import connect
import pandas as pd
import json
import requests

def look_over():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456789",db="user")
	cursor1 = con.cursor()
	sql = "select * from student"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res

app = Flask(__name__)

@app.route('/')
def hello() -> str:
	return "高高咯！"

# 调用日志记录函数
def log_request(req:'flask_request',res:str)->None:
	with open('view.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

# 进入网页的首页，数据返回gongnen1.html
@app.route('/base')
def entry_page() ->'html':
	return render_template('shouye.html',the_title='高高咯服务系统')

# 注册功能
@app.route('/zhuce',methods=["POST"])
def zhuce() -> "html":
	return render_template("zhuceyemian.html")

@app.route('/zhuce2',methods=["POST"])
def zhuce2():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456789",db="user")
	cursor2 = con.cursor()
	zhanghao = request.form.get("zhanghao")
	mima = request.form.get("mima")
	rowid =request.form.get("rowid")
	sql = "insert into useradmin set rowid='%s',uer_name='%s',password='%s'"% (rowid,zhanghao,mima)
	cursor2.execute(sql)
	con.commit()
	return render_template("zhucechenggong.html")


#选择功能服务
@app.route('/xuanze',methods=['POST'])
def xuanze() -> 'html':
	zhanghao = request.form.get("zhanghao") 
	mima = request.form.get("mima")
	a = panduan_login(zhanghao, mima)
	if a == "true":
		return render_template('xuanze.html',the_title ="请选择你需要的服务")
	else:
		return "登录失败"


# 广州天气查询
@app.route("/tianqi",methods=["post"])
def tianqi():
	key='030d60847cc2dbf652a0d1f7e0fce690'
	city='440100'
	extensions='base'
	a=weather(key,city,extensions)
	b=a['lives'][0]['city']
	c=a['lives'][0]['weather']
	d=a['lives'][0]['temperature']
	return render_template('weather.html',city=str(b),weather=str(c),temperature=str(d))


# 登陆
@app.route('/login',methods=['POST'])
def login_page() -> 'html':
	return render_template('login.html',the_title ="欢迎您登录高高咯定位服务！")


@app.route('/addlogin',methods=['POST'])
def addlogin() -> 'html':
	return render_template('gongnen1.html',the_title ="欢迎您进入高高咯定位系统！")





# 点击“搜索”后，调用高德api——geocode和around，数据返回gongnen2
@app.route('/search',methods=['POST'])
def go_search():
	address = request.form['address']
	codes = str(geocode(address)['geocodes'][0][ 'location'])

	location = codes
	types = request.form['types']
	results = around(location,types)['pois']


	names = []
	address2 = []
	for i in results:
		names.append(i['name'])
		address2.append(i['address'])
	combine = dict(zip(names,address2))

	log_request(request,results)
	return render_template('gongnen2.html',res=combine,the_title='为您返回的结果：')

# 图片识别
@app.route("/intopic",methods=['GET'])
def into_pic():
	return render_template("tupian.html")


@app.route("/pic",methods=['POST'])
def pic():
	image_url=request.form['pic']
	endpoint = "https://api-ggl.cognitiveservices.azure.com/"
	subscription_key = "055b3560ef704e958d9cc550a8afac51"
	analyze_url = endpoint + "vision/v3.1/analyze"   
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'visualFeatures': 'Categories,Description,Color'}
	data = {'url': image_url}
	response = requests.post(analyze_url, headers=headers,  params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	print(json.dumps(response.json()))
	image_caption = analysis["description"]["captions"][0]["text"].capitalize()
	confidence3 = analysis["description"]["captions"][0]["confidence"]
	return render_template('tupian.html',pic=str(image_caption),confidence3=str(confidence3),img_url1=image_url)



# 查看日志
@app.route('/viewlog')
def view_the_log() ->'html':
	with open('view.log',"r") as log:
		contents = []
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))

	titles = ('Form data','Remote_addr','User_agent','results')
	return render_template('viewlog.html',
		the_title='View Log',
		the_row_titles=titles,
		the_data=contents,)

if __name__=='__main__':
	app.run(debug=True)